<template>
  <div class="AudioDialogue">
    <div class="infoBox" v-show="isFold">
      <div class="infoTitle">
        <div class="title">录音信息</div>
        <div class="menu">
          <svg-icon
              @click="handleFold"
              :name="'icon-isFold'"
          ></svg-icon>
        </div>
      </div>
      <div class="infoContent">
        <ul>
          <li><span>客户电话：</span><span>{{ infoData.userNumber }}</span></li>
          <li><span>座席工号：</span><span>{{ infoData.agentNumber }}</span></li>
          <li><span>座席名称：</span><span>{{ infoData.agentName }}</span></li>
          <li><span>呼叫时间：</span><span>{{ infoData.start  }}</span></li>
          <li><span>接通时间：</span><span>{{ infoData.answer }}</span></li>
          <li><span>通话时长：</span><span>{{ formatTime }}</span></li>
          <li><span>uniqueld：</span><span>{{ props.dialogueData.asrId }}</span></li>
        </ul>
      </div>
    </div>
    <div class="dialogueBox">
      <div class="dialogueTitle">
        <div class="left">对话内容</div>
        <div class="right">
          <t-space style="gap: 3px;">
            <t-select class="c_select" v-model="selectValue" @change="handleSelect">
              <t-option key="" label="全部" value="" />
              <t-option key="1" label="座席" value="1" />
              <t-option key="2" label="用户" value="2" />
            </t-select>
            <t-input v-model="inputValue" class="c_input" @input="onInput" @enter="onEnter" placeholder="输入后回车定位" />
            <div class="round_icon">
              <svg-icon
                  :name="'icon-down'"
                  @click="nextMessage"
              ></svg-icon>
            </div>
            <div class="round_icon">
              <svg-icon
                  :name="'icon-up'"
                  @click="preventMessage"
              ></svg-icon>
            </div>
          </t-space>
        </div>
      </div>
      <div class="scrollBox" id="pel" @scroll="handleScroll">
<!--        折叠按钮-->
        <div class="foldMenu" v-if="!isFold" @click="handleFold">
          <svg-icon
              :name="'icon-isFold'"
          ></svg-icon>
        </div>

        <template v-if="isShowDialogue">
          <template v-for="item in dialogueState.dialogueData" :key="item.id">
            <!--          客户侧语音-->
            <div v-if="item.speaker === '2'" class="customBox">
              <div class="avatar">
                <svg-icon
                    :name="'icon-customAvatar'"
                ></svg-icon>
              </div>
              <div class="infoText">
                <div class="time">{{ formatMillisecond(item['start_time']) }}</div>
                <div class="c_info">
                  <div class="text" :id='item.id' :class="item.id === currentId ? 'activate' : ''">
                    <div :class="item.id === currentId ? 'activate' : ''">{{ item.text }}</div>
                    <template  v-if="item['scoreDetails'] && item['scoreDetails'].length > 0">
                      <div class="text_b" v-for="(e, index) in item['scoreDetails']" :key="e.id">
                        <div class="comment">评语：{{ e.remark }}</div>
                        <div class="b_flex">
                          <div class="left_b">{{ e.qualityRuleName }}：<span>{{ e.score }}分</span></div>
                          <div class="right_b" @click="openCorrectDialog(item, index)">评分纠正</div>
                        </div>
                      </div>
                    </template>
                  </div>
                  <div class="handle">
                    <div v-if="item['scoreDetails'] && item['scoreDetails'].length > 0">
                      <svg-icon :name="'icon-audioEdit'" @click="openCorrectDialog(item, 'zx')"></svg-icon>
                    </div>
                    <div>
                      <svg-icon :name="'icon-textPlay'" @click="audioPlay(item)"></svg-icon>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!--          座席侧语音-->
            <div v-if="item.speaker === '1'" class="seatsBox">
              <div class="infoText">
                <div class="time">{{ formatMillisecond(item['start_time']) }}</div>
                <div class="s_info">
                  <div class="handle">
                    <div v-if="item['scoreDetails'] && item['scoreDetails'].length > 0">
                      <!--                      暂不支持分开扣分默认纠正第一条数据-->
                      <svg-icon :name="'icon-audioEdit'" @click="openCorrectDialog(item, 'zx')"></svg-icon>
                    </div>
                    <div>
                      <svg-icon :name="'icon-textPlay'" @click="audioPlay(item)"></svg-icon>
                    </div>
                  </div>
                  <div class="text" :id='item.id' :class="item.id === currentId ? 'activate' : ''">
                    <div>{{ item.text }}</div>
                    <template  v-if="item['scoreDetails'] && item['scoreDetails'].length > 0">
                      <div class="text_b" v-for="(e, index) in item['scoreDetails']" :key="e.id">
                        <div class="comment">评语：{{ e.remark }}</div>
                        <div class="b_flex">
                          <div class="left_b">{{ e.qualityRuleName }}：<span>{{ e.score }}分</span></div>
                          <div class="right_b" @click="openCorrectDialog(item, index)">评分纠正</div>
                        </div>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
              <div class="avatar">
               <div class="bgc">
                 <svg-icon
                     :name="'icon-seatsAvatar'"
                 ></svg-icon>
               </div>
              </div>
            </div>
          </template>
        </template>
      </div>
    </div>
    <ScoreCorrectDialog
        :scoreVisible="scoreVisible"
        :correctData="correctData"
        @closeCorrectDialog="closeCorrectDialog"
        :isTransfer="isTransfer"
    ></ScoreCorrectDialog>
  </div>
</template>

<script setup>
import {computed, reactive, ref, toRaw, watch, inject} from "vue";
import dayjs from 'dayjs'
import ScoreCorrectDialog from './scoreCorrectDialog.vue'
import { MessagePlugin } from 'tdesign-vue-next';
import {usePageStore} from "@/pinia/page.js";
import {timeToMillisecond} from "../../../utils/tools";
const store = usePageStore()
const emits = defineEmits()

const props = defineProps({
  dialogueData: {
    type: Object,
    default: {}
  },
})

// 内容
const dialogueState = reactive({
  dialogueData: []
})

// 折叠
const isFold = ref(true)
const handleFold = () => {
  isFold.value = !isFold.value
}

const infoData = ref({})
const formatTime = ref('')

let flag = inject('showFlag')
let isShowDialogue = ref(false)
watch(() => flag.value, (newVal, oldVal) => {
  if(newVal) {
    console.log(' props.dialogueData',  props.dialogueData['recordingDetail'])
    infoData.value = props.dialogueData['recordingDetail']
    const second = infoData.value.duration
    const time = dayjs().startOf('day').second(second)
    formatTime.value = time.format('HH:mm:ss')

    targetIds.value = []
    currentId.value = null
    inputValue.value = ''
    selectValue.value = ''


  }
  dialogueState.dialogueData = props.dialogueData.utteranceVOList
  isShowDialogue.value = newVal
})


// 对话内容
const selectValue = ref('')
const inputValue = ref('')
const targetIds = ref([]) // 储存可匹配搜索条件的ID
const currentId = ref(null) // 所处当前条的ID
// 输入搜索条件
const onInput = () => {
  targetIds.value = []
  currentId.value = null
}
// 回车检索数据
const onEnter = () => {
  console.log('trigger enter', inputValue.value);
  currentId.value = null
  if(inputValue.value === '') return

  let data = []
  if(selectValue.value === '') { // 全部
    data = toRaw(dialogueState.dialogueData)
  } else { // 座席 | 客户
    data = toRaw(dialogueState.dialogueData).filter(item => item['speaker'] === selectValue.value)
  }
  const ids = []
  data.forEach(item => {
    if(item.text.indexOf(inputValue.value) !== -1) {
      ids.push(item.id)
    }
  })
  console.log('ids', ids)
  if(ids.length === 0) {
    targetIds.value = []
    return MessagePlugin.info('没有找到相关的结果')
  } else {
    targetIds.value = ids
    // 默认滚动到第一条数据位置
    currentId.value = currentId.value = targetIds.value[0]
    scrollFunction()
  }
};
// 上一条
const preventMessage = () => {
  if(inputValue.value === '' || targetIds.value.length === 0) return
  if(targetIds.value.length === 1) return MessagePlugin.info('没有更多') // 单条数据

  let index = targetIds.value.findIndex(item => item === currentId.value)
  if(index !== 0) {
    currentId.value = targetIds.value[index - 1]
  } else {
    currentId.value = targetIds.value[index]
  }
  scrollFunction()
}
// 下一条
const nextMessage = () => {
  if(inputValue.value === '' || targetIds.value.length === 0) return
  if(targetIds.value.length === 1) return MessagePlugin.info('没有更多')

  let index = targetIds.value.findIndex(item => item === currentId.value)
  if(targetIds.value.length !== index + 1) {
    currentId.value = targetIds.value[index + 1]
  } else {
    currentId.value = targetIds.value[index]
  }
  scrollFunction()
}
// 滚动方法
const scrollFunction = () => {
  if(!currentId.value) return
  let pel = document.getElementById('pel')
  let el = document.getElementById(currentId.value)
  pel.scrollTop = el.offsetTop - pel.offsetTop - (pel.offsetHeight / 2) + el.offsetHeight + 40;
}
// 搜索类型改变
const handleSelect = () => {
  targetIds.value = []
  currentId.value = null
  inputValue.value = ''
}

// 格式化时间
const formatMillisecond = computed(() => {
   return (millisecond) => {
     const time = dayjs().startOf('day').second(millisecond / 1000)
     return time.format('HH:mm:ss')
  }
})

// 评分纠正弹窗
const scoreVisible = ref(false)
const correctData = ref({})
const isTransfer = ref(false) // 点击icon 只能编辑转写纠正
const openCorrectDialog = (data, index) => {
  const info = toRaw(data)
  if(index === 'zx') {
    correctData.value = {
      utteranceId: info.id,
      text: info.text,
      asrId: info.asrId,
      templateId: info.templateId,
    }
    isTransfer.value = true
  } else {
    correctData.value = {
      utteranceId: info.id,
      text: info.text,
      asrId: info.asrId,
      templateId: info.templateId,
      score: info['scoreDetails'][index].score,
      remark: info['scoreDetails'][index].remark,
      qualityRuleId: info['scoreDetails'][index].qualityRuleId,
      qualityRuleName: info['scoreDetails'][index].qualityRuleName,
    }
    isTransfer.value = false
  }


  scoreVisible.value = true
}
const closeCorrectDialog = (flag) => { // flag 是否更新数据
  scoreVisible.value = false
  isTransfer.value = false
  if(flag === 1) {
    // 重置页面数据
    store.$patch({ isResetQuality: true })
    // 重新请求数据
    emits('getDetailData')
  }
}

const hiddenScroll = ref(true) // 自动播放取消定位
// 用户手动滚动对话框
const handleScroll= () => {
  // hiddenScroll.value = false
}

// 判断当前对话进度
watch(() => store.currentPlayTime, (newVal, oldVal) => {
  if(targetIds.value.length > 0) return
  if(store.isSinglePlay) return;
  let time = newVal * 1000
  getId(time)

})
const getId = (time) => {
  let data = toRaw(dialogueState.dialogueData)
  let ary = data.filter(item => {
    if(item['start_time'] <= time && time < item['end_time']) {
      return item
    }
  })

  currentId.value = ary.length > 0 ? ary[0].id : null
  scrollFunction()
}
// 点击对话播放图标
const audioPlay = (item) => {
  let obj = {
    start: item['start_time'] / 1000,
    end: item['end_time'] / 1000
  }
  store.$patch({ isSinglePlay: true })
  currentId.value = item.id
  store.$patch({ audioPlayInterval: obj})
}
</script>

<style lang="scss" scoped>
.AudioDialogue {
  display: flex;
  height: 100%;
  .infoBox {
    width: 297px;
    margin-right: 1px;
    overflow-y: auto;
    background-color: rgba(252, 252, 252, 1);
    .infoTitle {
      height: 45px;
      padding: 0 22px 0 22px;
      line-height: 45px;
      display: flex;
      .title {
        font-size: 12px;
        font-weight: 600;
        color: rgba(77, 77, 77, 1);
      }
      .menu {
        margin-left: auto;
        .svg-icon {
          cursor: pointer;
          height: 20px;
          width: 20px;
        }
      }
    }
    .infoContent {
      padding-top: 6px;
      padding-left: 22px;
      ul {
        li {
          list-style: none;
          margin-bottom: 16px;
          span:nth-child(1) {
            font-size: 12px;
            font-weight: 400;
            color: rgba(89, 89, 89, 1);
          }
          span:nth-child(2) {
            font-size: 12px;
            font-weight: 600;
            color: rgba(89, 89, 89, 1);
          }
        }
      }
    }

  }
  .dialogueBox {
    flex: 1;
    margin-right: 1px;
    .dialogueTitle {
      height: 45px;
      background-color: rgba(255, 255, 255, 1);
      margin-bottom: 1px;
      display: flex;
      //justify-content: center;
      align-items: center;
      padding: 0 20px 0 21px;
      .left {
        flex: 1;
        min-width: 200px;
        font-size: 12px;
        font-weight: 600;
        color: rgba(77, 77, 77, 1);
      }
      .right {
        margin-left: auto;
        .c_select {
          width: 55px;
          height: 28px;
          :deep(.t-input__wrap) {
            height: 28px;
            .t-input {
              height: 28px;
              border-radius: 28px;
              background: rgba(242, 242, 242, 1);
              padding: 0 6px;
              .t-input__inner {
                font-size: 12px;
                font-weight: 400;
                color: rgba(92, 91, 91, 1);
              }
              .t-input__suffix:not(:empty) {
                margin-left: 0 !important;
              }
            }
          }
        }
        .c_input {
          :deep(.t-input) {
            height: 28px;
            width: 138px;
            border: 1px solid rgba(229, 229, 229, 1);
            border-radius: 28px;
            .t-input__inner {
              height: 28px;
              width: 138px;
            }
          }
        }
        .round_icon {
          height: 28px;
          width: 28px;
          border-radius: 28px;
          background-color: rgba(242, 242, 242, 1);
          cursor: pointer;
          .svg-icon {
            height: 28px;
            width: 28px;
          }
        }
      }
    }
    .scrollBox {
      height: calc(100% - 46px);
      padding-bottom: 20px;
      opacity: 1;
      overflow-y: auto;
      background: rgba(252, 252, 252, 1);
      position: relative;
      .foldMenu {
        cursor: pointer;
        position: fixed;
        top: calc(50% + 47px);
        //transform: translateY(-50%);
        width: 48px;
        height: 47px;
        border-radius: 5px;
        background: rgba(255, 255, 255, 1);

        border: 1px solid rgba(235, 235, 235, 1);

        box-shadow: 0 2px 8px 1px rgba(0, 0, 0, 0.08);
        display: flex;
        justify-content: center;
        align-items: center;
        .svg-icon {
          height: 20px;
          width: 20px;
        }
      }

      .customBox {
        padding-top: 20px;
        display: flex;
        .avatar {
          padding: 0 12px 0 20px;
          .svg-icon {
            height: 36px;
            width: 36px;
          }
        }
        .infoText {
          flex: 1;
          .c_info {
            display: flex;
            //justify-content: right;
            .text {
              border-radius: 0 8px 8px 16px;
              background: rgba(232, 232, 232, 1);
              overflow: hidden;
              .text_b {
                min-width: 254px;
                margin-top: 10px;
                height: 47px;
                padding: 6px 8px 0 9px;
                border-radius: 6px;
                background: rgba(255, 255, 255, 1);
                font-size: 11px;
                font-weight: 400;
                .comment {
                  font-size: 11px;
                  font-weight: 400;
                  color: rgba(79, 79, 79, 1);
                }
                .b_flex {
                  margin-top: 3px;
                  display: flex;
                  .left_b {
                    flex: 1;
                    font-size: 11px;
                    font-weight: 400;
                    color: rgba(79, 79, 79, 1);
                    span {
                      font-size: 11px;
                      font-weight: 400;
                      color: rgba(227, 60, 100, 1);
                    }
                  }
                  .right_b {
                    margin-left: auto;
                    font-size: 11px;
                    font-weight: 400;
                    color: rgba(97, 158, 255, 1);
                    cursor: pointer;
                  }
                }
              }
            }
            .handle {
              display: none;
              //width: 55px;
              height: 22px;
              border-radius: 4px;
              background: rgba(252, 252, 252, 1);
              border: 0.8px solid rgba(212, 212, 212, 1);
              box-shadow: 0 2px 4px  rgba(232, 232, 232, 0.25);
              margin-right: 9px;
              div {
                float: left;
                width: 50%;
                text-align: center;
                padding: 0 2.5px;
              }
              div:nth-child(2) {
                border-left: 0.8px solid rgba(212, 212, 212, 1);
              }
              .svg-icon {
                cursor: pointer;
                height: 16px;
                width: 16px
              }
            }
          }
          .c_info:hover {
            .handle {
              display: block;
            }
          }
        }
      }
      .seatsBox {
        padding-top: 20px;
        display: flex;
        .avatar {
          .bgc {
            height: 36px;
            width: 36px;
            border-radius: 18px;
            background-color: rgba(245, 248, 255, 1);
          }
          padding: 0 12px 0 20px;
          .svg-icon {
            padding: 10px 11px 10px 11px;
            height: 36px;
            width: 36px;
          }
        }
        .infoText {
          flex: 1;
          //text-align: right;
          .time {
            text-align: right;
          }
          .s_info {
            display: flex;
            justify-content: right;
            .text {
              border-radius: 8px 0 16px  8px;
              background-color: rgba(209, 227, 255, 1);
              .text_b {
                min-width: 254px;
                margin-top: 10px;
                height: 47px;
                padding: 6px 8px 0 9px;
                border-radius: 6px;
                background: rgba(255, 255, 255, 1);
                font-size: 11px;
                font-weight: 400;
                .comment {
                  font-size: 11px;
                  font-weight: 400;
                  color: rgba(79, 79, 79, 1);
                }
                .b_flex {
                  margin-top: 3px;
                  display: flex;
                  .left_b {
                    flex: 1;
                    font-size: 11px;
                    font-weight: 400;
                    color: rgba(79, 79, 79, 1);
                    span {
                      font-size: 11px;
                      font-weight: 400;
                      color: rgba(227, 60, 100, 1);
                  }
                  }
                  .right_b {
                    margin-left: auto;
                    font-size: 11px;
                    font-weight: 400;
                    color: rgba(97, 158, 255, 1);
                    cursor: pointer;
                  }
                }
              }
            }
            .handle {
              display: none;
              //width: 55px;
              height: 22px;
              border-radius: 4px;
              background: rgba(252, 252, 252, 1);
              border: 0.8px solid rgba(212, 212, 212, 1);
              box-shadow: 0 2px 4px  rgba(232, 232, 232, 0.25);
              margin-right: 9px;
              div {
                float: left;
                width: 50%;
                text-align: center;
                padding: 0 2.5px;
              }
              div:nth-child(2) {
                border-left: 0.8px solid rgba(212, 212, 212, 1);
              }
              .svg-icon {
                cursor: pointer;
                height: 16px;
                width: 16px
              }
            }
          }
          .s_info:hover {
            .handle {
              display: block;
            }
          }
        }
      }
      .time {
        font-size: 12px;
        font-weight: 400;
        color: rgba(12, 13, 14, 1);
        height: 22px;
        line-height: 22px;
      }
      .text {
        display: inline-block;
        max-width: 70%;
        padding: 10px 13px;
        font-size: 12px;
        font-weight: 400;
        color: rgba(41, 41, 41, 1);
      }
    }
  }
}
.activate {
  background: rgba(30, 117, 254, 1) !important;
  color: rgba(255, 255, 255, 1) !important;
}
</style>

